package Components.image.frame
{
	import Components.config.ImageConfig;
	
	import events.GlobalEvent;
	import events.SDispatcher;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import mx.graphics.codec.PNGEncoder;
	
	import utils.BitmapDataUtils;
	import utils.FileUtils;
	
	public class BitmapFrame extends Sprite
	{
		private var _loader:Loader;
		private var _path:String = "";
		
		private var _container:Sprite;
		
		private var _rect:Rectangle;
		private var _bitmap:Bitmap;
		private var _shape:Shape;
		
		public function BitmapFrame( path:String )
		{
			super();
			_path = path;
			init();
		}
		
		private function init():void
		{
			_container = new Sprite();
			_container.mouseChildren = false;
			_container.mouseEnabled = false;
			addChild( _container );
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onLoaded );
			_loader.load( new URLRequest( _path ) );
		}
		
		public function out( action:String, direction:String, index:int ):void
		{
			var bitmapData:BitmapData = new BitmapData( _rect.width, _rect.height, true, 0 );
			bitmapData.copyPixels( _bitmap.bitmapData, _rect, new Point() );
			var png:PNGEncoder = new PNGEncoder();
			var byte:ByteArray = png.encode( bitmapData );
			
			var name:String = action+"_"+direction+"_"+index;
			
			var x:int = _rect.x - _bitmap.width/2 + ImageConfig.xOffset;
			var y:int = _rect.y - _bitmap.height/2 + ImageConfig.yOffset;
			var s:String = "var " + name + "_x:int=";
			s += x;
			s += ";var ";
			s += name;
			s += "_y:int=";
			s += y;
			s += ";";
			ImageConfig.outAS += s;
			
			FileUtils.writeToFile( ImageConfig.out_dir + "/image/" + name +".png", byte );
			
			SDispatcher.dispatchEvent( new GlobalEvent( GlobalEvent.ONE_BITMAP_COMPLETE ) );
		}
		
		public function destroy():void
		{
			if( parent ) parent.removeChild( this );
			
		}
		
		private function onLoaded( e:Event ):void
		{
			_bitmap = _loader.content as Bitmap;
			_container.addChild( _bitmap );
			
			_shape = new Shape();
			_container.addChild( _shape );
			_shape.graphics.lineStyle( 1, 0x0099CC );
			
			_rect = BitmapDataUtils.getColorRect( _bitmap.bitmapData );
			_shape.graphics.drawRect( _rect.x, _rect.y, _rect.width, _rect.height );
			
			_container.x = -int(_bitmap.width/2);
			_container.y = -int(_bitmap.height/2);
		}
	}
}

















